package com.gagc.zookeeper.service.impl;

import com.gagc.zookeeper.service.LogService;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * create by lorne on 2018/1/29
 */
@Service
public class LogServiceImpl implements LogService {


    @Autowired
    private ZkClient zkClient;

    private List<String> list = new CopyOnWriteArrayList<>();

    @Override
    public boolean set(String name) {
        if(!zkClient.exists("/test")) {
            zkClient.createPersistent("/test");
        }
        zkClient.create("/test/"+name,name, CreateMode.EPHEMERAL);
        zkClient.subscribeDataChanges("/test/" + name, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                list.add("handleDataChange->"+s+",val:"+o);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                list.add("handleDataDeleted->"+s);
            }
        });
        return true;
    }

    @Override
    public List<String> logs() {
        return list;
    }


    @Override
    public boolean setVal(String name, String val) {
        zkClient.writeData("/test/"+name,val);
        return true;
    }

    @Override
    public boolean del(String name) {
        return zkClient.delete("/test/"+name);
    }
}
